import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/LoginPage.vue'
import Layout from '../views/LayoutPage.vue'

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/home',
        name: 'Home',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: '/dashboard',
                name: 'Dashboard',
                component: () => import('../views/DashBoard.vue'),
                meta: { title: '控制台' }
            },
            {
                path: '/user',
                name: 'User',
                component: () => import('../views/UserPage.vue'),
                meta: { title: '用户管理' }
            },
            {
                path: '/product',
                name: 'Product',
                component: () => import('../views/ProductPage.vue'),
                meta: { title: '商品管理' }
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    if (to.path !== '/login' && !token) {
        next('/login')
    } else {
        next()
    }
})

export default router